#include "WarGameLib.h"


wgImage::wgImage()
{
	image = 0;
}


int wgImage::getWidth()
{
	return image->w;
}
int wgImage::getHeight()
{
	return image->h;
}

bool wgImage::Load(const char *filename)
{
	image = IMG_Load(filename);
	if(image != 0)
		return true;
	cout << IMG_GetError() << endl;
	return false;
}

wgImage::~wgImage()
{
	if(image!=0)
	{
		SDL_FreeSurface(image);
		image = 0;
	}
}

unsigned wgImage::getPixel(int i)
{
	int stride = image->format->BytesPerPixel;
	if(stride == 1)
	{
		unsigned char* lum = (unsigned char*) image->pixels;
		unsigned char gray = lum[i];
		return gray << 16 | gray << 8 | gray;
	}
	else
	{
		unsigned * pPixels = (unsigned*)image->pixels;
		return pPixels[i];
	}
}

void wgImage::getPixel(int i, int *pRed, int* pGreen, int *pBlue, int *pAlpha)
{
	unsigned pixel = getPixel(i);
	if(pRed != 0)
		*pRed = pixel & image->format->Rmask;
	if(pGreen != 0)
		*pGreen = pixel & image->format->Gmask;
	if(pBlue != 0)
		*pBlue = pixel & image->format->Bmask;
	if(pAlpha != 0)
		*pAlpha = pixel & image->format->Amask;

}


bool wgImage::CreateTexture()
{ 

   glPixelStorei(GL_UNPACK_ALIGNMENT,4);

	glGenTextures(1, &textureID);
	cout << "Texture ID = " << textureID << endl;
	UseTexture();


	GLenum format = image->format->Amask == 0 ? GL_RGB : GL_RGBA;

	glTexImage2D(GL_TEXTURE_2D, 0, image->format->BytesPerPixel, getWidth(), getHeight(), 0, format, GL_UNSIGNED_BYTE, image->pixels);
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
	glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

	return true;
}
void wgImage::UseTexture()
{
	glBindTexture(GL_TEXTURE_2D, textureID);
}
